package com.mall.seckill_mall.controller;

import com.mall.seckill_mall.common.RedisPreffix;
import com.mall.seckill_mall.common.Result;
import com.mall.seckill_mall.entity.User;
import com.mall.seckill_mall.enums.CodeMessage;
import com.mall.seckill_mall.service.UserService;
import com.mall.seckill_mall.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @GetMapping("/{userId}")
    public Result getUser(@PathVariable("userId") String userId) {
        User user = userService.getUser(userId);
        if(user == null) {
            return ResultUtil.error(CodeMessage.USER_NOT_EXISTS);
        }
        return ResultUtil.success(user);
    }

    @PostMapping("")
    public Result registerUser(@Valid User user) {
        boolean ok = userService.registerUser(user);
        if(!ok) {
            return ResultUtil.error(CodeMessage.SERVER_ERROR);
        }
        return ResultUtil.success(user.getUserId());
    }

    @PostMapping("/login")
    public Result loginUser(HttpServletResponse response
            , @CookieValue(value = "user_token", required = false) String userToken
            , @RequestParam("userId") String userId
            , @RequestParam("userPassWord") String userPassWord) {
        // 校验用户名/密码参数
        if(StringUtils.isEmpty(userId.replaceAll(" ", ""))
                || StringUtils.isEmpty(userPassWord.replaceAll(" ", ""))) {
            CodeMessage codeMessage = CodeMessage.BIND_ERROR;
            String message = codeMessage.getMessage().concat(": 请输入用户名或密码");
            return ResultUtil.error(codeMessage.getCode(), message);
        }
        // 校验是否已登录
        String userKey = RedisPreffix.USER_PREFFIX;
        User user = null;
        if(!StringUtils.isEmpty(userToken)) {
            user = userService.getUserByToken(userToken);
            if(user != null) {
                return ResultUtil.error(CodeMessage.REPEAT_LOGIN);
            }
        }
        // 登录
        user = userService.loginUser(userId, userPassWord);
        user.setUserPassWord("");
        userToken = UUID.randomUUID().toString().replaceAll("-", "");
        Cookie cookie = new Cookie("user_token", userToken);
        cookie.setMaxAge(30 * 60);
        cookie.setPath("/");
        response.addCookie(cookie);
        userService.setUserByToken(userToken, user);
        return ResultUtil.success(user);
    }

    @GetMapping("/logout")
    public Result logOut(@CookieValue("user_token") String userToken, HttpServletResponse response) {
        if(StringUtils.isEmpty(userToken)) {
            return ResultUtil.error(CodeMessage.USER_NOT_EXISTS);
        }
        userService.deleteUserByToken(userToken);
        Cookie cookie = new Cookie("user_token", "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return ResultUtil.success();
    }

    @PutMapping("/{userId}")
    public Result updatePassword(@PathVariable("userId") String userId
            , @RequestParam("oldPassWord") String oldPassWord
            , @RequestParam("passWord") String passWord
            , HttpServletResponse response, HttpServletRequest re
            , @CookieValue("user_token") String userToken) {
        if(StringUtils.isEmpty(userId.replaceAll(" ", ""))
                || StringUtils.isEmpty(oldPassWord.replaceAll(" ", ""))
                || StringUtils.isEmpty(passWord.replaceAll(" ", ""))) {
            CodeMessage codeMessage = CodeMessage.BIND_ERROR;
            String message = codeMessage.getMessage().concat(": 请输入用户名或密码");
            return ResultUtil.error(codeMessage.getCode(), message);
        }
        userService.updatePassWord(userId, oldPassWord, passWord);
        userService.deleteUserByToken(userToken);
        Cookie cookie = new Cookie(userToken, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return ResultUtil.success();
    }

    @PutMapping("/balance/{userId}")
    public Result updateBalance(@PathVariable("userId") String userId
            , @RequestParam("balance") double balance) {
        if(StringUtils.isEmpty(userId.replaceAll(" ", ""))) {
            CodeMessage codeMessage = CodeMessage.BIND_ERROR;
            String message = codeMessage.getMessage().concat(": 请输入用户名");
            return ResultUtil.error(codeMessage.getCode(), message);
        }
        User user = userService.getUser(userId);
        if(user == null) {
            return ResultUtil.error(CodeMessage.USER_NOT_EXISTS);
        }
        double cur = user.getUserBalance();
        double currentBalance = parseFen(parseYuan(cur) + parseYuan(balance));
        userService.updateBalance(userId, currentBalance);
        return ResultUtil.success(currentBalance);
    }
    private int parseYuan(double yuan) {
        return (int) (yuan * 100);
    }

    private double parseFen(int fen) {
        return new BigDecimal(fen).divide(new BigDecimal(100)).setScale(2).doubleValue();
    }
}
